package com.gnuc.thoth.app.screens;

import android.app.ExpandableListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gnuc.thoth.R;
import com.gnuc.thoth.app.Main;
import com.gnuc.thoth.framework.Thoth;
import com.gnuc.thoth.framework.ThothLog;
import com.gnuc.thoth.framework.callbacks.ThothCallback;
import com.gnuc.thoth.framework.db.ThothDB;

public class MessagingMain extends ExpandableListActivity
{
	private ThothExpandableListAdapter	elAdapter;
	private ExpandableListView				elView;
	private Context							elContext;
	private static MessagingMain			instance	= null;
	private static int						tV_DOS, tV_DIS, tV_DOM, tV_DIM = 0;
	
	public static MessagingMain getInstance()
	{
		if (instance == null)
			instance = new MessagingMain();
		return instance;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		try
		{
			setContentView(R.layout.msg_main);
			elContext = instance = this;
			elView = getExpandableListView();
			elAdapter = new ThothExpandableListAdapter();
			elView.setOnGroupClickListener(new OnGroupClickListener()
			{
				@Override
				public boolean onGroupClick(ExpandableListView elv, View view, int pos, long row)
				{
					return false;
				}
			});
			elView.setOnChildClickListener(new ExpandableListView.OnChildClickListener()
			{
				@Override
				public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
				{
					// Toast.makeText(elContext, "" + v.getTag(Thoth.APP), Toast.LENGTH_LONG).show();
					return true;
				}
			});
			elView.addHeaderView(View.inflate(this, R.layout.msg_layout, null), null, false);
			elView.setAdapter(elAdapter);
			elView.setDivider(getResources().getDrawable(R.drawable.row_gradient1));
			elView.setDividerHeight(1);
			elView.setChildDivider(getResources().getDrawable(R.drawable.row_gradient2));
			elView.setFooterDividersEnabled(true);
		}
		catch (Exception e)
		{
			ThothLog.e(e);
			Main.getInstance().mainHandler.sendEmptyMessage(-1);
		}
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		Thoth.cx = this;
		updateStatistics();
	}
	
	@Override
	public void onPause()
	{
		super.onPause();
	}
	
	public class ThothExpandableListAdapter extends BaseExpandableListAdapter
	{
		private Integer[]		explist_parents;
		private String[][][]	explist_children;
		
		public ThothExpandableListAdapter()
		{
			explist_parents = new Integer[]{R.layout.explist_m_s_top_out, R.layout.explist_m_s_top_in, R.layout.explist_m_m_top_out, R.layout.explist_m_m_top_in};
			explist_children = new String[][][]{{{"", ""}, {"", ""}, {"", ""}, {"", ""}, {"", ""}}, {{"", ""}, {"", ""}, {"", ""}, {"", ""}, {"", ""}}, {{"", ""}, {"", ""}, {"", ""}, {"", ""}, {"", ""}}, {{"", ""}, {"", ""}, {"", ""}, {"", ""}, {"", ""}}};
		}
		
		@Override
		public Object getChild(int groupPosition, int childPosition)
		{
			return explist_children[groupPosition][childPosition];
		}
		
		@Override
		public long getChildId(int groupPosition, int childPosition)
		{
			return childPosition;
		}
		
		@Override
		public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
		{
			RelativeLayout child = (RelativeLayout) View.inflate(elContext, R.layout.explist_m_childrow, null);
			String cPN = explist_children[groupPosition][childPosition][0];
			String cPQ = explist_children[groupPosition][childPosition][1];
			cPN = (cPN.equals("")) ? " - " : cPN;
			cPQ = (cPQ.equals("")) ? "( - )" : "(" + cPQ + " times.)";
			TextView tv = ((TextView) child.findViewById(R.id.t_m_child_name_label_id));
			tv.setText(cPN);
			tv.setVisibility(View.VISIBLE);
			tv = (TextView) child.findViewById(R.id.t_m_child_quantity_label_id);
			tv.setText(cPQ);
			tv.setVisibility(View.VISIBLE);
			child.findViewById(R.id.t_m_child_name_label_pb).setVisibility(View.INVISIBLE);
			child.findViewById(R.id.t_m_child_quantity_label_pb).setVisibility(View.INVISIBLE);
			child.setTag(Thoth.APP, cPN);
			return child;
		}
		
		@Override
		public int getChildrenCount(int groupPosition)
		{
			return explist_children[groupPosition].length;
		}
		
		@Override
		public Object getGroup(int groupPosition)
		{
			return explist_parents[groupPosition];
		}
		
		@Override
		public int getGroupCount()
		{
			return explist_parents.length;
		}
		
		@Override
		public long getGroupId(int groupPosition)
		{
			return groupPosition;
		}
		
		@Override
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
		{
			return (RelativeLayout) View.inflate(elContext, (Integer) getGroup(groupPosition), null);
		}
		
		@Override
		public boolean hasStableIds()
		{
			return true;
		}
		
		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition)
		{
			return true;
		}
	}
	
	public void updateStatistics()
	{
		updateDataSet(elAdapter, Thoth.Settings.APP_LOG_FILTER, new ThothCallback()
		{
			@Override
			public void handle(boolean result)
			{
				runOnUiThread(new Runnable()
				{
					@Override
					public void run()
					{
						elAdapter.notifyDataSetChanged();
					}
				});
			}
		});
	}
	
	void updateDataSet(ThothExpandableListAdapter tela, int filter, ThothCallback callback)
	{
		int x;
		boolean result = false;
		Cursor cR = null;
		ThothDB dbA = new ThothDB(elContext);
		try
		{
			dbA.open();
			SQLiteDatabase db = dbA.getDb();
			cR = db.query(true, ThothDB.table_APP_MSGS_STAT, null, ThothDB.col_A_S_M_FILTER + "=" + filter, null, null, null, null, null);
			if (cR != null && cR.moveToFirst())
			{
				tV_DOS = cR.getInt(cR.getColumnIndexOrThrow(ThothDB.col_A_S_M_TOTAL_OUTBOUND_MSGS));
				tV_DIS = cR.getInt(cR.getColumnIndexOrThrow(ThothDB.col_A_S_M_TOTAL_INBOUND_MSGS));
				tV_DOM = cR.getInt(cR.getColumnIndexOrThrow(ThothDB.col_A_S_M_TOTAL_OUTBOUND_MSGM));
				tV_DIM = cR.getInt(cR.getColumnIndexOrThrow(ThothDB.col_A_S_M_TOTAL_INBOUND_MSGM));
				
				runOnUiThread(new Runnable()
				{
					@Override
					public void run()
					{
						((TextView) findViewById(R.id.t_m_s_total_out_data_id)).setText(String.valueOf(tV_DOS));
						((TextView) findViewById(R.id.t_m_s_total_in_data_id)).setText(String.valueOf(tV_DIS));
						((TextView) findViewById(R.id.t_m_m_total_out_data_id)).setText(String.valueOf(tV_DOM));
						((TextView) findViewById(R.id.t_m_m_total_in_data_id)).setText(String.valueOf(tV_DIM));
					}
				});
			}
			tela.explist_children = new String[][][]{{{"", ""}, {"", ""}, {"", ""}, {"", ""}, {"", ""}}, {{"", ""}, {"", ""}, {"", ""}, {"", ""}, {"", ""}}, {{"", ""}, {"", ""}, {"", ""}, {"", ""}, {"", ""}}, {{"", ""}, {"", ""}, {"", ""}, {"", ""}, {"", ""}}};
			cR = db.query(true, ThothDB.table_APP_MSGS_RANK, null, "(" + ThothDB.col_A_R_M_TYPE + "=0" + ")" + "AND" + "(" + ThothDB.col_A_R_M_FILTER + "=" + filter + ")", null, null, null, ThothDB.col_A_R_M_CONTACTED + " DESC", null);
			if (cR != null && cR.moveToFirst())
			{
				x = 0;
				do
					tela.explist_children[0][x++] = new String[]{lookupContact(cR.getString(cR.getColumnIndexOrThrow(ThothDB.col_A_R_M_CONTACT))), cR.getString(cR.getColumnIndexOrThrow(ThothDB.col_A_R_M_CONTACTED)), ""};
				while (cR.moveToNext());
			}
			cR = db.query(true, ThothDB.table_APP_MSGS_RANK, null, "(" + ThothDB.col_A_R_M_TYPE + "=1" + ")" + "AND" + "(" + ThothDB.col_A_R_M_FILTER + "=" + filter + ")", null, null, null, ThothDB.col_A_R_M_CONTACTED + " DESC", null);
			if (cR != null && cR.moveToFirst())
			{
				x = 0;
				do
					tela.explist_children[1][x++] = new String[]{lookupContact(cR.getString(cR.getColumnIndexOrThrow(ThothDB.col_A_R_M_CONTACT))), cR.getString(cR.getColumnIndexOrThrow(ThothDB.col_A_R_M_CONTACTED)), ""};
				while (cR.moveToNext());
			}
			cR = db.query(true, ThothDB.table_APP_MSGS_RANK, null, "(" + ThothDB.col_A_R_M_TYPE + "=2" + ")" + "AND" + "(" + ThothDB.col_A_R_M_FILTER + "=" + filter + ")", null, null, null, ThothDB.col_A_R_M_CONTACTED + " DESC", null);
			if (cR != null && cR.moveToFirst())
			{
				x = 0;
				do
					tela.explist_children[2][x++] = new String[]{lookupContact(cR.getString(cR.getColumnIndexOrThrow(ThothDB.col_A_R_M_CONTACT))), cR.getString(cR.getColumnIndexOrThrow(ThothDB.col_A_R_M_CONTACTED)), ""};
				while (cR.moveToNext());
			}
			cR = db.query(true, ThothDB.table_APP_MSGS_RANK, null, "(" + ThothDB.col_A_R_M_TYPE + "=3" + ")" + "AND" + "(" + ThothDB.col_A_R_M_FILTER + "=" + filter + ")", null, null, null, ThothDB.col_A_R_M_CONTACTED + " DESC", null);
			if (cR != null && cR.moveToFirst())
			{
				x = 0;
				do
					tela.explist_children[3][x++] = new String[]{lookupContact(cR.getString(cR.getColumnIndexOrThrow(ThothDB.col_A_R_M_CONTACT))), cR.getString(cR.getColumnIndexOrThrow(ThothDB.col_A_R_M_CONTACTED)), ""};
				while (cR.moveToNext());
			}
			result = true;
		}
		catch (Exception e)
		{
			// ThothDebug.e(e);
		}
		finally
		{
			cR.close();
			dbA.close();
			callback.handle(result);
		}
		return;
	}
	
	String lookupContact(String lookupKey)
	{
		String cLookupKey = lookupKey;
		Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey);
		Cursor cR = null;
		try
		{
			cR = getContentResolver().query(lookupUri, new String[]{Contacts.DISPLAY_NAME}, null, null, null);
			cR.moveToFirst();
			cLookupKey = cR.getString(0);
		}
		catch (Exception exp)
		{}
		finally
		{
			if (cR != null)
				cR.close();
		}
		return cLookupKey;
	}
}
